package br.ucb.tcc.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * 
 * Classe que monta o Excel
 * 
 * @author italoricci
 *
 * @param <T>
 */
public class ExcelUtil<T> {

	public void montarExcel(Collection<T> generics, String... atributos) {
		try {
			HSSFWorkbook work = new HSSFWorkbook();
			HSSFSheet sheet1 = work.createSheet(Constantes.PLANILHA_NOME);
			HSSFCellStyle estilo = work.createCellStyle();
			PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
			int row = 0;
			for (T generic : generics) {
				HSSFRow linha = sheet1.createRow(row);
				for (int i = 0; i < atributos.length; i++) {
					HSSFCell celula = linha.createCell(i);
					Object property = propertyUtilsBean.getProperty(generic, atributos[i]);
					celula.setCellStyle(estilo);
					if (property != null) {
						celula.setCellValue(property.toString());
					} else {
						celula.setCellValue("");
					}
				}
				row++;
			}
			File file = new File(Constantes.PATH + Constantes.NOME_EXCEL_GERADO);
			if (file.exists()) {
				file.delete();
				file.createNewFile();
			}
			FileOutputStream fileInputStream = new FileOutputStream(file);
			work.write(fileInputStream);
			fileInputStream.flush();
			fileInputStream.close();
			System.out.println("OK!");
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
